package ee.android.kinokavad.fragments;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;

import ee.android.kinokavad.App;
import ee.android.kinokavad.R;
import ee.android.kinokavad.activities.KinoKavadActivity;
import ee.android.kinokavad.adapters.MovieAdapter;
import ee.android.kinokavad.data.Movie;
import ee.android.kinokavad.interfaces.OnMovieClickListener;

public class MoviesFragment extends SherlockFragment implements OnChildClickListener, OnGroupClickListener {

	private static final String TAG = MoviesFragment.class.getSimpleName();
	private static final String GENRE_OTHER = "Ülejäänud";
	private static final String [] GENRES = {"Eesti", "Animatsioon", "Ooper", 
		"Kontsert", "Dokumentaal", "Muinasjutt", "Kogupere", "Ajalooline eepos",
		"Õudus", "Romantika", "Ulmefilm", "Sport", "Teater", "Action", "Draama", 
		"Komöödia", "Seiklus", GENRE_OTHER};
	
	private static final int MENU_SHOW_SELECTED = 0;
	private static final int MENU_SHOW_ALL = 1;
	private MovieAdapter mAdapter;

	private OnMovieClickListener mListener;

	public static Fragment newInstance(Bundle args) {
		Fragment f = new MoviesFragment();
		f.setArguments(args);
		return f;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnMovieClickListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnMovieClickListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.movies_fragment, container, false);
		initViews(view);
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		setHasOptionsMenu(true);
		init();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getSherlockActivity().getSupportActionBar().setSubtitle("Filmid");
	}


	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.movies_menu, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onChildClick(ExpandableListView arg0, View arg1, int groupPosition, int childPosition, long id) {

		Movie movie = (Movie) mAdapter.getChild(groupPosition, childPosition);
		mListener.onMovieClicked(movie.getNetId());
		return true;
	}

	private void initViews(View view) {

		ExpandableListView listView = (ExpandableListView) view.findViewById(R.id.moviesList);
		listView.setAdapter(mAdapter);
		for (int groupPosition = 0; groupPosition < mAdapter.getGroupCount(); groupPosition++) {
			listView.expandGroup(groupPosition);
		}
		registerForContextMenu(listView);
		listView.setOnChildClickListener(this);
		listView.setOnGroupClickListener(this);

	}


	private void init() {

		App kinokavad = (App) getActivity().getApplication();
		kinokavad.getDataController().open();
		List<Movie> movies = kinokavad.getDataController().loadAllMoviesFromDatabase();
		kinokavad.getDataController().closeRequest();
		Map<String, ArrayList<Movie>> genresMap = generateGenres(movies);
		List<ArrayList<Movie>> moviesByGenre = new ArrayList<ArrayList<Movie>>();
		List<String> genres = new ArrayList<String>();
		for (Entry<String, ArrayList<Movie>> entry : genresMap.entrySet()) {
			if (entry.getValue().size() != 0) {
				genres.add(entry.getKey());
				moviesByGenre.add(entry.getValue());
			}
		}

		mAdapter = new MovieAdapter(getActivity(), genres, moviesByGenre);

	}

	private Map<String, ArrayList<Movie>> generateGenres(List<Movie> movies) {

		Map<String, ArrayList<Movie>> map = new LinkedHashMap<String, ArrayList<Movie>>();
		for (String genre : GENRES) {
			map.put(genre, new ArrayList<Movie>());
		}
		for (Movie movie : movies) {
			boolean genreSet = false;
			for (String genre : map.keySet()) {
				if (movie.getGenre().contains(genre)) {
					map.get(genre).add(movie);
					genreSet = true;
					break;
				}
			}
			if (!genreSet)
				map.get(GENRE_OTHER).add(movie);
		}
		return map;

	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		//Disable collapsing groups
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		ExpandableListView.ExpandableListContextMenuInfo info =
				(ExpandableListView.ExpandableListContextMenuInfo) menuInfo;

		int type = ExpandableListView.getPackedPositionType(info.packedPosition);

		int group =	ExpandableListView.getPackedPositionGroup(info.packedPosition);
		int child =	ExpandableListView.getPackedPositionChild(info.packedPosition);

		// Only create a context menu for child items
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) 
		{
			Movie movie = (Movie) mAdapter.getChild(group, child);
			menu.setHeaderTitle(movie.getTitle());
			menu.add(0, MENU_SHOW_ALL, 0, "Näita kõiki seansse");
			menu.add(0, MENU_SHOW_SELECTED, 1, "Näita valitud kino(de) seansse");

		} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			return;
		}

		super.onCreateContextMenu(menu, v, menuInfo);

	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {

		ExpandableListContextMenuInfo info = 
				(ExpandableListContextMenuInfo) item.getMenuInfo();

		int type = ExpandableListView.getPackedPositionType(info.packedPosition);

		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) 
		{
			int group = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			int child = ExpandableListView.getPackedPositionChild(info.packedPosition);
			Movie movie = (Movie) mAdapter.getChild(group, child);
			KinoKavadActivity.replaceFragment(getActivity(), 
					MovieSessionFragment.newInstance(movie.getNetId(), item.getItemId() == MENU_SHOW_SELECTED), true, false);

			return true;
		} 

		return false;
	}

}
